package org.cloudie.docs.editor.client.widgets;

import org.cloudie.docs.editor.client.content.dialogs.SelectImageDialog;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FocusPanel;

public class ImageBox extends Composite {
	
  private String value, urlPattern, defaultId;
  private FocusPanel panel;
  private String[] ids;
	
  public ImageBox(String urlPattern, String defaultId, String[] ids) {
	this.ids = ids;
	this.urlPattern = urlPattern;
	this.defaultId = defaultId;
    panel = new FocusPanel();
    panel.setTitle("Click to select image.");
    panel.setPixelSize(100, 18);
    panel.setStylePrimaryName("cloudie-ImageBox-Empty");
    panel.addClickHandler(new ClickHandler() {
	    @Override
		public void onClick(ClickEvent event) {
		  SelectImageDialog.get(ImageBox.this.urlPattern, ImageBox.this.ids).center(
		  new SelectionHandler<String>() {
			@Override
			public void onSelection(SelectionEvent<String> event) {
			  setValue(event.getSelectedItem());
			}
		  });
		}
    });
    initWidget(panel);
    setValue(defaultId);
  }

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
	if (value == null && defaultId != null) {
	  value = defaultId;
	}
    this.value = value;
    if (value == null) {
      panel.setStylePrimaryName("cloudie-ImageBox-Empty");
      panel.getElement().getStyle().setBackgroundImage("");
    } else {
      String url = urlPattern.replace("%1", value);
      panel.setStylePrimaryName("cloudie-ImageBox");
      panel.getElement().getStyle().setBackgroundImage("url(" + url + ")");
    }
  }

}

